//定义系统托盘
import type {MenuItem, MenuItemConstructorOptions} from "electron";
import {BrowserWindow, dialog, Menu} from "electron";
import packageInfo from "../../../package.json";
import * as diyConst from "../config/const";
import {trayURL} from "../config/staticPath";

function platform() {
	if (process.platform === "darwin") return "Mac OS";
	return process.platform;
}

const type = platform();
const release = process.getSystemVersion();
const arch = process.arch;

function info() {
	dialog
		.showMessageBox({
			title: "关于",
			type: "info",
			message: `${packageInfo.title}`,
			detail: `版本信息：${packageInfo.version}\n引擎版本：${process.versions.v8}\n当前系统：${type} ${arch} ${release}`,
			noLink: true,
			buttons: ["官网", "确定"],
		})
		.then((r) => {
			console.log(r);
			if (r.response === 0) {
				const win = new BrowserWindow({width: 800, height: 600});
				// Load a remote URL
				win.loadURL(diyConst.GwLink);
				// Or load a local HTML file
				// win.loadFile('index.html')
			}
		});
}

export function sleep(ms: number) {
	return new Promise((resolve) => {
		setTimeout(resolve, ms);
	});
}

export function createTrayWindow() {
	const win = new BrowserWindow({
		width: 300,
		height: 160,
		show: false,
		opacity: 0,
		resizable: false,
		movable: false,
		frame: false,
		hiddenInMissionControl: true,
		skipTaskbar: true,
		visualEffectState: "active",
		vibrancy: "menu",
	});
	win.loadURL(trayURL);

	win.on("blur", async () => {
		let opacity = 1;
		while (opacity > 0) {
			await sleep(10);
			opacity -= 0.1;
			win.setOpacity(opacity);
		}
		win.hide();
	});

	win.on("show", async () => {
		let opacity = 0;
		while (opacity < 1) {
			await sleep(10);
			opacity += 0.2;
			win.setOpacity(opacity);
		}
		win.focus();
	});
	return win;
}

const menu: Array<MenuItemConstructorOptions | MenuItem> = [
	{
		label: "快速重启",
		accelerator: "F5",
		role: "reload",
	},

	{
		label: "编辑",
		submenu: [
			{
				label: "撤销",
				accelerator: "CmdOrCtrl+Z",
				role: "undo",
			},
			{
				label: "重做",
				accelerator: "Shift+CmdOrCtrl+Z",
				role: "redo",
			},
			{
				label: "剪切",
				accelerator: "CmdOrCtrl+X",
				role: "cut",
			},
			{
				label: "复制",
				accelerator: "CmdOrCtrl+C",
				role: "copy",
			},
			{
				label: "粘贴",
				accelerator: "CmdOrCtrl+V",
				role: "paste",
			},
		],
	},
	{
		label: "关于我们",
		click: info,
	},
	{
		label: "退出",
		accelerator: "CmdOrCtrl+F4",
		role: "close",
	},
];

export default Menu.buildFromTemplate(menu);
